package com.yingpai.fitness.dvp_2_0.main.activity.mine;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.haibin.calendarview.Calendar;
import com.haibin.calendarview.CalendarView;
import com.lzy.okgo.model.Response;
import com.yingpai.fitness.R;
import com.yingpai.fitness.dvp_2_0.common.activity.CommonActivity;
import com.yingpai.fitness.dvp_2_0.common.adapter.BaseAdapterHelper;
import com.yingpai.fitness.dvp_2_0.common.adapter.QuickAdapter;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.callback.Callback;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.request.RequestType;
import com.yingpai.fitness.dvp_2_0.common.util.constant.Contacts;
import com.yingpai.fitness.dvp_2_0.common.view.XGridView;
import com.yingpai.fitness.dvp_2_0.main.activity.mine.integral.IntegralMallActivity;
import com.yingpai.fitness.dvp_2_0.main.activity.mine.integral.IntegralMallCouponActivity;
import com.yingpai.fitness.dvp_2_0.main.activity.mine.integral.IntegralMallShopDetailActivity;
import com.yingpai.fitness.dvp_2_0.main.activity.mine.integral.IntegralMallVipCardActivity;
import com.yingpai.fitness.dvp_2_0.main.activity.mine.integral.IntegralRuleActivity;
import com.yingpai.fitness.dvp_2_0.main.bean.SignIntegralBean;
import com.yingpai.fitness.dvp_2_0.main.bean.SignMonthBean;
import com.yingpai.fitness.dvp_2_0.main.bean.SignTodayBean;
import com.yingpai.fitness.dvp_2_0.main.util.DialogUtil;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Constant;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Url;
import com.yingpai.fitness.dvp_2_0.main.widget.LoopView;
import com.yingpai.fitness.dvp_2_0.main.widget.round.RCRelativeLayout;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by ASUS on 2018/11/20.
 */

public class SignActivity extends CommonActivity {
    @BindView(R.id.day_count)
    TextView dayCount;
    @BindView(R.id.integration)
    TextView integration;
    @BindView(R.id.date)
    TextView date;
    @BindView(R.id.calendarView)
    CalendarView calendarView;
    @BindView(R.id.sign)
    Button sign;
    @BindView(R.id.right_tv)
    TextView right_tv;
    @BindView(R.id.gridview)
    XGridView gridView;
    @BindView(R.id.pointmall)
    LinearLayout mlayout_pointmall;
    private Map<String, Calendar> map;
    //    private int mYear;
//    private int mMonth;
    private LoopView picker_year;
    private LoopView picker_month;
    private TextView dialog_date;
    private List<String> yearList = new ArrayList();
    private List<String> monthList = new ArrayList();
    private int yearPos = 0;
    private int monthPos = 0;
    private int minYear = 2018; // min year
    private int maxYear = 2099; // max year
    private QuickAdapter<SignIntegralBean.DataBean> quickAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStatusFlag(Contacts.NORMAL_STATUS);
        setContentView(R.layout.dvp_2_0_activity_sign);
    }

    @Override
    protected void initView() {
        setTitle("每日签到");
        right_tv.setText("规则说明");

        quickAdapter = new QuickAdapter<SignIntegralBean.DataBean>(this, R.layout.item_integral_mall) {
            @Override
            protected void convert(BaseAdapterHelper helper, SignIntegralBean.DataBean item) {
                LinearLayout integral_ll = helper.getView(R.id.integral_ll);
                RCRelativeLayout rc_layout = helper.getView(R.id.rc_layout);
                rc_layout.setTopLeftRadius(3);
                rc_layout.setTopRightRadius(3);
                rc_layout.setBottomLeftRadius(3);
                rc_layout.setBottomRightRadius(3);
                ImageView photo = helper.getView(R.id.photo);
                Glide.with(context)
                        .load(item.getPhotoUrl().split(",")[0])
                        .error(R.mipmap.default_small_bg)
                        .into(photo);
                helper.setText(R.id.title, item.getName());
                helper.setText(R.id.integral, item.getExchange()+"");
                if(helper.getPosition()==3){
                    integral_ll.setVisibility(View.INVISIBLE);
                }else{
                    integral_ll.setVisibility(View.VISIBLE);
                }
            }
        };
        gridView.setAdapter(quickAdapter);
        gridView.setFocusable(false);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == 3) {
                    startActivity(IntegralMallActivity.class);
                } else {
                    if (quickAdapter.getItem(position).getDictVal() == Constant.NUM_1) {
                        Bundle bundle = new Bundle();
                        bundle.putString("id", quickAdapter.getItem(position).getId());
                        startActivity(IntegralMallVipCardActivity.class, bundle);
                    } else if (quickAdapter.getItem(position).getDictVal() == Constant.NUM_2) {
                        Bundle bundle = new Bundle();
                        bundle.putString("id", quickAdapter.getItem(position).getId());
                        startActivity(IntegralMallCouponActivity.class, bundle);
                    } else if (quickAdapter.getItem(position).getDictVal() == Constant.NUM_3) {
                        Bundle bundle = new Bundle();
                        bundle.putString("id", quickAdapter.getItem(position).getId());
                        startActivity(IntegralMallShopDetailActivity.class, bundle);
                    }
                }

            }
        });

        date.setText(calendarView.getCurYear() + "年" + calendarView.getCurMonth() + "月");
    }

    @Override
    protected void initData() {
        finalOkGo.requestEncrypt(RequestType.POSTENCRYPT, Contacts.HOST_SERVER + Url.GET_SIGN_INFO, null, Url.GET_SIGN_INFO, new Callback<SignTodayBean>() {
            @Override
            public void onSuccess(SignTodayBean signTodayBean) {
                if (signTodayBean.getCode().equals(Constant.REQUEST_SUCCESS_0)) {
                    dayCount.setText(signTodayBean.getData().getKeepSignDays() + "");
                    integration.setText(signTodayBean.getData().getPoint() + "");
                    if (signTodayBean.getData().getIsSignToday() == Constant.NUM_0) {
                        sign.setText("立即签到");
                    } else if (signTodayBean.getData().getIsSignToday() == Constant.NUM_1) {
                        sign.setText("已签到");
                    }
                } else {
                    showToast(signTodayBean.getMessage() + "");
                }
            }
        });

        finalOkGo.requestEncrypt(RequestType.POSTENCRYPT, Contacts.HOST_SERVER + Url.SIGN_INTEGRAL_RECOMMONED,
                null, Url.SIGN_INTEGRAL_RECOMMONED, new Callback<SignIntegralBean>() {
                    @Override
                    public void onSuccess(SignIntegralBean signIntegralBean) {
                        if (signIntegralBean.getCode().equals(Constant.REQUEST_SUCCESS_0)) {
                            if(signIntegralBean.getData()!=null && signIntegralBean.getData().size()>0){
                                mlayout_pointmall.setVisibility(View.VISIBLE);
                                quickAdapter.clear();
                                quickAdapter.addAll(signIntegralBean.getData());
                                quickAdapter.notifyDataSetChanged();
                            }else{
                                mlayout_pointmall.setVisibility(View.GONE);
                            }
                        } else {
                            showToast(signIntegralBean.getMessage() + "");
                            mlayout_pointmall.setVisibility(View.GONE);
                        }
                    }
                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        mlayout_pointmall.setVisibility(View.GONE);
                    }
                });

        calendarView.setOnMonthChangeListener(new CalendarView.OnMonthChangeListener() {
            @Override
            public void onMonthChange(int year, int month) {
//                mYear = year;
//                mMonth = month;
                date.setText(year + "年" + month + "月");
                map = new HashMap<>();
                HashMap<String, Object> params = new HashMap<>();
                if(month>9){
                    params.put("date", year + "-" + month);
                }else{
                    params.put("date", year + "-0" + month);
                }
                finalOkGo.requestEncrypt(RequestType.POSTENCRYPT, Contacts.HOST_SERVER +
                        Url.GET_MONTH_SIGN_INFO, params, Url.GET_MONTH_SIGN_INFO, new Callback<SignMonthBean>() {
                    @Override
                    public void onSuccess(SignMonthBean signMonthBean) {
                        if (signMonthBean.getCode().equals(Constant.REQUEST_SUCCESS_0)) {
                            int yearBean = Integer.parseInt(signMonthBean.getData().getMonth().split("-")[0]);
                            int monthBean = Integer.parseInt(signMonthBean.getData().getMonth().split("-")[1]);
                            for (int i = 0; i < signMonthBean.getData().getDays().size(); i++) {
                                map.put(getSchemeCalendar(yearBean, monthBean, signMonthBean.getData().getDays().get(i)).toString(),
                                        getSchemeCalendar(yearBean, monthBean, signMonthBean.getData().getDays().get(i)));
                            }
                            calendarView.clearSchemeDate();
                            calendarView.setSchemeDate(map);
                        } else {
                            showToast(signMonthBean.getMessage() + "");
                        }
                    }
                });
            }
        });
    }

    @Override
    @OnClick({R.id.date, R.id.sign, R.id.right_tv, R.id.exchange, R.id.integral_mall})
    public void onViewClicked(View view) {
        super.onViewClicked(view);
        switch (view.getId()) {
            case R.id.date:
                DialogUtil.getInstance().showBottomDialog(this, R.layout.dialog_sign_calendar);
                View dialog_layout = DialogUtil.getInstance().dialog_bottom_layout;
                dialog_layout.findViewById(R.id.close).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        DialogUtil.getInstance().dialog_bottom.dismiss();
                    }
                });

                dialog_date = dialog_layout.findViewById(R.id.dialog_date);
                dialog_date.setText(calendarView.getCurYear() + "年" + calendarView.getCurMonth() + "月");

                picker_year = dialog_layout.findViewById(R.id.picker_year);
                picker_month = dialog_layout.findViewById(R.id.picker_month);

                picker_year.setLoopListener(new LoopView.LoopScrollListener() {
                    @Override
                    public void onItemSelect(int item) {
                        yearPos = item;
                        dialog_date.setText(dialog_date.getText().toString().replace(dialog_date.getText().toString().substring(0, dialog_date.getText().toString().indexOf("年") + 1), yearList.get(item)));
                    }
                });

                picker_month.setLoopListener(new LoopView.LoopScrollListener() {
                    @Override
                    public void onItemSelect(int item) {
                        monthPos = item;
                        dialog_date.setText(dialog_date.getText().toString().replace(dialog_date.getText().toString().substring(dialog_date.getText().toString().indexOf("年") + 1), monthList.get(item)));
                    }
                });

                initPickerViews();

                dialog_layout.findViewById(R.id.sure).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        calendarView.scrollToCalendar(Integer.parseInt(yearList.get(yearPos).split("年")[0]), Integer.parseInt(monthList.get(monthPos).split("月")[0]), 1);
                        DialogUtil.getInstance().dialog_bottom.dismiss();
                    }
                });

                break;
            case R.id.sign:
                showDialog(context, null);
                finalOkGo.requestEncrypt(RequestType.POSTENCRYPT, Contacts.HOST_SERVER + Url.SAVE_SIGN_INFO, null, Url.SAVE_SIGN_INFO, new Callback<SignTodayBean>() {
                    @Override
                    public void onSuccess(SignTodayBean saveSignBean) {
                        if (saveSignBean.getCode().equals(Constant.REQUEST_SUCCESS_0)) {
                            dayCount.setText(saveSignBean.getData().getKeepSignDays() + "");
                            integration.setText(saveSignBean.getData().getPoint() + "");
                            if (saveSignBean.getData().getIsSignToday() == Constant.NUM_0) {
                                sign.setText("立即签到");
                            } else if (saveSignBean.getData().getIsSignToday() == Constant.NUM_1) {
                                sign.setText("已签到");
                            }
                            calendarView.scrollToCurrent();
                            int year = calendarView.getCurYear();
                            int month = calendarView.getCurMonth();
                            int day = calendarView.getCurDay();
                            map.put(getSchemeCalendar(year, month, day).toString(),
                                    getSchemeCalendar(year, month, day));
                            calendarView.setSchemeDate(map);
                            DialogUtil.getInstance().showCenterDialog(context, R.layout.dialog_shop_pay_success);
                            View dialog_center_layout = DialogUtil.getInstance().dialog_center_layout;
                            dialog_center_layout.findViewById(R.id.close).setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    DialogUtil.getInstance().dialog_center.dismiss();
                                }
                            });
                            TextView title = dialog_center_layout.findViewById(R.id.title);
                            title.setText("签到成功");
                            TextView message = dialog_center_layout.findViewById(R.id.message);
                            message.setText("恭喜您增加" + saveSignBean.getData().getSignIntegral() + "积分");
                            EventBus.getDefault().post(Constant.UPDATA_INFOMATION);
                        } else {
                            showToast(saveSignBean.getMessage() + "");
                        }
                        dismissDialog();
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        dismissDialog();
                    }
                });
                break;
            case R.id.right_tv:
                startActivity(IntegralRuleActivity.class);
                break;
            case R.id.exchange:
                startActivity(IntegralMallActivity.class);
                break;
            case R.id.integral_mall:
                startActivity(IntegralMallActivity.class);
                break;
        }
    }

    private Calendar getSchemeCalendar(int year, int month, int day) {
        Calendar calendar = new Calendar();
        calendar.setYear(year);
        calendar.setMonth(month);
        calendar.setDay(day);
        return calendar;
    }

    private String format2LenStr(int num) {

        return (num < 10) ? "0" + num : String.valueOf(num);
    }

    private void initPickerViews() {

        int yearCount = maxYear - minYear;

        for (int i = 0; i < yearCount; i++) {
            yearList.add(format2LenStr(minYear + i) + "年");
        }

        for (int j = 0; j < 12; j++) {
            monthList.add(format2LenStr(j + 1) + "月");
        }

        yearPos = yearList.indexOf(calendarView.getCurYear() + "年");
        monthPos = monthList.indexOf(calendarView.getCurMonth() + "月");

        picker_year.setDataList((ArrayList) yearList);
        picker_year.setInitPosition(yearPos);

        picker_month.setDataList((ArrayList) monthList);
        picker_month.setInitPosition(monthPos);
    }
}
